package cn.qj.ymcc.mq;

import cn.qj.ymcc.constants.BusinessConstants;
import cn.qj.ymcc.domain.MessageSms;
import cn.qj.ymcc.domain.MessageStation;
import cn.qj.ymcc.dto.MessageSMSDto;
import cn.qj.ymcc.dto.MessageStationDto;
import cn.qj.ymcc.dto.UserPhoneDto;
import cn.qj.ymcc.service.IMessageSmsService;
import cn.qj.ymcc.service.IMessageStationService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 消费短信推送消息
* */
@Slf4j
@RocketMQMessageListener(topic = BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TOPIC,
                         selectorExpression = BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TAGS_SMS,
                         consumerGroup = "service-common-consumer-sms")
@Component
public class MQConsumerSms implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        String s = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        MessageSMSDto messageSMSDto = JSONObject.parseObject(s, MessageSMSDto.class);
        //存到数据库
        List<MessageSms> messageSmsList = new ArrayList<>();
        List<UserPhoneDto> userPhoneDtos = messageSMSDto.getUserPhoneDto();
        userPhoneDtos.forEach(userPhoneDto -> {
            MessageSms messageSms = new MessageSms();
            BeanUtils.copyProperties(messageSMSDto, messageSms);
            messageSms.setUserId(userPhoneDto.getUserId());
            messageSms.setPhone(userPhoneDto.getPhone());
            messageSms.setIp(userPhoneDto.getIp());
            messageSms.setSendTime(new Date());
            messageSmsList.add(messageSms);
        });
        messageSmsService.insertBatch(messageSmsList);
        log.info("短信推送结果:{}",messageSmsList);
    }
}
